$(document).ready(
        function() {

            var clickHandler = function() {
                if (!$(this).hasClass("ui-state-active")) {
                    chrome.extension.sendRequest({
                        type: "jump",
                        id: this.id.split("-")[1]
                    }, function(response) {
                    });
                }
            };

            chrome.extension.sendRequest({
                type: "list"
            }, function(response) {
                $.each(response.playlist, function(i, track) {
                    $("#playlist").append($("<li />", {
                        "id": "track-" + track.id,
                        "title": track.title,
                        "class": "ui-state-default ui-widget-content"
                    }).html(track.title));
                });
                $("#playlist li").hover(
                        function() {
                            $(this).addClass("ui-state-hover").removeClass(
                                    "ui-state-default");
                        },
                        function() {
                            $(this).addClass("ui-state-default").removeClass(
                                    "ui-state-hover");
                        }).click(clickHandler);
            });

            var port = chrome.extension.connect();

            port.onMessage.addListener(function(message) {
                switch (message.type) {
                    case "status":
                        $("#tracklist").scrollTop(
                                $("#track-" + message.track.id).position().top
                                - $("#tracklist").offset().top);
                    case "change":
                        $("#playlist li").addClass("ui-state-default").removeClass(
                                "ui-state-active");
                        $("#track-" + message.track.id).addClass("ui-state-active")
                                .removeClass("ui-state-default");
                        break;
                }
            });

        });